package com.ydd.common.utils;

import com.ydd.common.constent.RequestContext;
import com.ydd.common.exception.BusinessException;
import com.ydd.common.exception.ErrRespCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.Optional;

@Component
@Slf4j
public class LoginUtil {


    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private JwtUtil jwtUtils;


    public Optional<String> getToken() {
        HttpServletRequest request = RequestContext.getCurrentRequest();
        if (request != null) {
            return getTokenFromHeader(request);
        }
        return Optional.empty();
    }
    public String createToken(String userName,Integer userId,String platform,Integer timeout) {
        String token = jwtUtils.createToken(userName,userId,platform,timeout);
        return token;
    }

    private Optional<String> getTokenFromHeader(HttpServletRequest request) {
        String header = request.getHeader("Authorization");
        if (header != null && !header.isEmpty()) {
            //去掉前缀
//            if (header.startsWith("")) {
//                return Optional.of(header.substring("".length()));
//            }
            return Optional.ofNullable(header);
        }
        return Optional.empty();
    }



    private String getTokenUserId() {
        String authorization = getToken().get();
        if (StringUtils.isEmpty(authorization)) {
            throw new BusinessException(ErrRespCode.REGISTER_ERROR_TOKEN_EXIT.getName());
        }
        String userId = jwtUtils.getUserId(authorization);
        if(StringUtils.isEmpty(userId)){
            throw new BusinessException(ErrRespCode.REGISTER_ERROR_TOKEN.getName());
        }
        return userId;
    }
}
